package com.system.travel.modules.system.service.impl;

import com.system.travel.common.exception.ServiceException;
import com.system.travel.common.utils.JwtUtils;
import com.system.travel.modules.system.entity.SysUser;
import com.system.travel.modules.system.service.AuthService;
import com.system.travel.modules.system.service.SysUserService;
import com.system.travel.modules.system.vo.LoginVO;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private SysUserService userService;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public LoginVO login(String username, String password) {
        try {
            // 创建未认证的Authentication
            UsernamePasswordAuthenticationToken authenticationToken = 
                new UsernamePasswordAuthenticationToken(username, password);

            // 认证
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            
            // 认证成功后，将认证信息存入SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 生成token
            String token = jwtUtils.generateToken(username);

            // 获取用户信息
            SysUser user = userService.getByUsername(username);
            if (user == null) {
                throw new ServiceException("用户不存在");
            }

            // 获取用户详细信息
            Map<String, Object> userInfo = userService.getUserInfo(user.getId());

            // 构建登录返回信息
            LoginVO loginVO = new LoginVO();
            loginVO.setUserId(user.getId());
            loginVO.setUsername(user.getUsername());
            loginVO.setNickname(user.getNickname());
            loginVO.setAvatar(user.getAvatar());
            loginVO.setToken(token);
            
            // 从userInfo中获取角色和权限
            @SuppressWarnings("unchecked")
            List<String> roles = (List<String>) userInfo.get("roles");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> permissions = (List<Map<String, Object>>) userInfo.get("permissions");
            
            // 设置角色和权限
            loginVO.setRoles(roles);
            loginVO.setMenuPermissions(permissions);

            return loginVO;
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细异常信息
            throw new ServiceException("用户名或密码错误: " + e.getMessage());
        }
    }

    @Override
    public void logout() {
        SecurityContextHolder.clearContext();
    }
} 